<?php
namespace addon\cms\logic;
use app\common\logic\LogicBase;
use tpfcore\Core;
use think\Db;

class CustomForm extends LogicBase
{
    public function saveCustomForm($data){
    	$validate=Core::addonValidate($this->name);
        $scene=isset($data['id'])?"edit":"add";
        $validate_result = $validate->scene($scene)->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $validate->getError(), null];
        }

        /* 
            创建表 
            基础字段 
            id        主键 int  自动递增
            uid       用户ID  int
            openid    第三方开放id   varchar(64)
            status    状态0/1
            datetime  添加时间  varchar(30)
        */
        
        try {
            if(empty($data['id'])){
                $table_name=$data['name'];
                $table=DB_PREFIX.strtolower($data['table']);
                $table_sql=<<<sql
CREATE TABLE IF NOT EXISTS `{$table}` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uid` int(11) DEFAULT 0 COMMENT '用户ID',
  `openid` varchar(64) DEFAULT NULL COMMENT '第三方开放id',
  `status` tinyint(4) DEFAULT '1' COMMENT '状态0/1',
  `datetime` varchar(30) DEFAULT 0 COMMENT '添加时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='{$table_name}';
sql;
                Db::execute($table_sql);
            }

            $result=Core::loadAddonModel($this->name)->saveObject($data);

            if($result){
                return [RESULT_SUCCESS,"操作成功",url('cms/CustomForm/index')];
            }else{
                return [RESULT_ERROR,"操作失败",null];
            }

        } catch (\Exception $e) {
            return [RESULT_ERROR,"sql语句操作失败",null];
        }
    }

    public function getCustomForm($data=[]){
        return Core::loadAddonModel($this->name)->getList($data);
    }

    public function delCustomForm($data){
        $list = $this->getCustomForm(["where"=>["id"=>$data['id']]]);

        $table_name = DB_PREFIX.$list[0]['table'];

        Db::execute("DROP TABLE $table_name");
        
        $result=self::deleteObject($data,true);
        
        if($result){
            return [RESULT_SUCCESS,"操作成功",url('cms/CustomForm/index')];
        }else{
            return [RESULT_ERROR,"操作失败",null];
        }
    }

    public function getCustomFieldsList($_data)
    {
        $CustomForm = Core::loadAddonModel('CustomForm')->getOneObject(['id'=>$_data['form_id']]);
        if (empty($CustomForm)) {
            return [RESULT_ERROR, '没有对应的表单'];
        }

        return $CustomForm->fields;
    }
}